<?php

namespace util;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;

class ALiYunSmsTool
{
    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi Client
     */
    public static function createClient($accessKeyId, $accessKeySecret)
    {
        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * 使用STS鉴权方式初始化账号Client，推荐此方式。
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @param string $securityToken
     * @return Dysmsapi Client
     */
    public static function createClientWithSTS($accessKeyId, $accessKeySecret, $securityToken)
    {
        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret,
            // 必填，您的 Security Token
            "securityToken" => $securityToken,
            // 必填，表明使用 STS 方式
            "type" => "sts"
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * @param string[] $args
     * @return array
     */
    public static function main($args)
    {
        // 请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html
        $client = self::createClient($args['accessKeyID'], $args['accessKeySecret']);
        $sendSmsRequest = new SendSmsRequest([
            "signName" => $args['signName'],
            "templateCode" => $args['template'],
            "phoneNumbers" => $args['mobile'],
            "templateParam" => $args['templateParam']
        ]);
        $runtime = new RuntimeOptions([]);
        $resp = $client->sendSmsWithOptions($sendSmsRequest, $runtime);
        if ($resp->statusCode == 200) {
            return [true, $args['dev'] ? $args['templateParam'] : 'Success'];
        }
        return [false, $resp->statusCode];
    }
}